package com.shuhe.domain.mxgc;

import com.alibaba.fastjson.JSON;
import com.shuhe.JettyServer;
import com.shuhe.common.Tools;
import com.shuhe.metastore.DBSql;
import com.shuhe.metastore.MetaMysql;
import org.apache.log4j.Logger;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.Security;
import java.sql.Connection;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.shuhe.common.CommonFunction.closeDb;
import static com.shuhe.common.HttpClient.*;

public class HttpPush {
    private static Logger logger = Logger.getLogger(HttpPush.class);
    public static Properties globalProperties = new Properties();

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    //方法
    public void HttpPush(ArrayList<PushApiConfig> pushApiConfigs) throws Exception {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        Connection metaConn = null;
        Connection dbConn = null;
        try {
            metaConn = MetaMysql.connect();
            dbConn = DBSql.connect();
            for (int i = 0; i < pushApiConfigs.size(); i++) {
                Date date = new Date();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String timestamp = format.format(date);
                //第一步：获取token()
                String url = pushApiConfigs.get(i).getTokenAddr();
//                String token_para = pushApiConfigs.get(i).getTokenPara().replace("@timestamp", timestamp);
                HashMap<String, String> parms = new HashMap<>();
                parms.put("EnterpriseId", "HBYT_CYYC");
                parms.put("Timestamp", timestamp);

                String requestMethod = pushApiConfigs.get(i).getTokenMethod().toUpperCase();
                String reponseStr = "";
                if (requestMethod.equals("GET")) {

                    reponseStr = getHttp3(url, parms);
                }
                //解析结果
//                reponseStr = "{\n" +
//                        "    \"success\": true,\n" +
//                        "    \"message\": null,\n" +
//                        "    \"errCode\": \"0\",\n" +
//                        "    \"resCode\": 1,\n" +
//                        "    \"apiVersion\": \"1\",\n" +
//                        "    \"timestamp\": 1733454221,\n" +
//                        "    \"data\": \"{\\\"token\\\":\\\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
//                        .eyJlbnRJZCI6IkhCWVRfQ1lZQyIsImlwQWRkcmVzcyI6IjEwLjE4OC4xNzguMjAiLCJuYmYiOjE3MzM0NTQyMjEsImV4cCI6MTczMzQ3MjIyMSwiaXNzIjoiSFNFX0RDIiwiYXVkIjoiRU5UX0RDIn0.ad87Ri6Nn3xNh77AUYnU-PaqBYflem0rPDIBr6YUW8U\\\",\\\"publicKey\\\":\\\"04E99DFE0EAADF2873803010C8278FB8C2BC0C3AB2DF9146AEE11CF8DAE006556EF32FB9B82AEFC72B9D3EBA189429452918A12F994FD6FFC8E26C4C9C40BB39E0\\\"}\"\n" +
//                        "}";
                JSONObject obj = new JSONObject(reponseStr);
                String tokenDatas = obj.getString("data");
                JSONObject obj1 = new JSONObject(tokenDatas);
                String token = obj1.getString("token");
                String publicKey = obj1.getString("publicKey");
                Boolean success = obj.getBoolean("success");

                if (success) {
                    //第二步：推送数据
                    url = pushApiConfigs.get(i).getApiServerAddr();

                    HashMap<String, String> requestPropertysData = new HashMap<>();
                    String apiHead = pushApiConfigs.get(i).getApiHead();
                    HashMap<String, String> apiHeads = getKeyValues(apiHead);
                    for (Map.Entry<String, String> entry : apiHeads.entrySet()) {
                        requestPropertysData.put(entry.getKey(), entry.getValue().replace("@token", token));
                    }
                    //组装data数据,保持顺序
                    LinkedHashMap<String, String> requestBodys = new LinkedHashMap<>();
                    String sql = "select * from " + pushApiConfigs.get(i).getFullTableName();
                    ResultSet rs = DBSql.querySql(dbConn, sql);
                    ArrayList<DataObject> dataObjects = new ArrayList<>();
                    while (rs.next()) {
                        String tagName = rs.getString("tag_name");
                        String tagTime = rs.getString("tag_time");
                        String tagValue = rs.getString("tag_value");
                        if (!tagName.equals("")) {
                            DataObject dataObject = new DataObject(tagName, tagTime, tagValue);
                            dataObjects.add(dataObject);
                        }
                    }
                    LinkedHashMap<String, ArrayList<DataObject>> datas = new LinkedHashMap<>();
                    datas.put("datas", dataObjects);
                    if (dataObjects.size() > 0) {
                        requestBodys.put("Data", Tools.sm2Encrypt(publicKey, JSON.toJSONString(datas).replace("\"",
                                "\'")));
                        requestBodys.put("EnterpriseId", "HBYT_CYYC");
                        requestBodys.put("PublicKey", publicKey);     //缺
                        requestBodys.put("Timestamp", timestamp);
                        String requestBodysStr = JSON.toJSONString(requestBodys);

                        LinkedHashMap<String, String> requestBodys1 = new LinkedHashMap<>();
                        requestBodys1.put("Data", JSON.toJSONString(datas));
                        requestBodys1.put("EnterpriseId", "HBYT_CYYC");
                        requestBodys1.put("PublicKey", publicKey);     //缺
                        requestBodys1.put("Timestamp", timestamp);
                        String requestBodysStr1 = JSON.toJSONString(requestBodys1);


                        WriteLog(uuid, pushApiConfigs.get(i).getServiceId(), pushApiConfigs.get(i).getUserName(),
                                format.format(new Date()), pushApiConfigs.get(i).getServiceCode(), requestBodysStr1,
                                "", "", "", "", "0", metaConn);
                        reponseStr = postHttp(url, requestBodysStr, requestPropertysData);

                        //第三步：删除数据
                        //解析结果
//                        reponseStr = "{\n" +
//                                "    \"success\": true,\n" +
//                                "    \"message\": null,\n" +
//                                "    \"errCode\": \"0\",\n" +
//                                "    \"resCode\": 1,\n" +
//                                "    \"apiVersion\": \"1\",\n" +
//                                "    \"timestamp\": 1733454221,\n" +
//                                "    \"data\": \"{\\\"token\\\":\\\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
//                                .eyJlbnRJZCI6IkhCWVRfQ1lZQyIsImlwQWRkcmVzcyI6IjEwLjE4OC4xNzguMjAiLCJuYmYiOjE3MzM0NTQyMjEsImV4cCI6MTczMzQ3MjIyMSwiaXNzIjoiSFNFX0RDIiwiYXVkIjoiRU5UX0RDIn0.ad87Ri6Nn3xNh77AUYnU-PaqBYflem0rPDIBr6YUW8U\\\",\\\"publicKey\\\":\\\"04E99DFE0EAADF2873803010C8278FB8C2BC0C3AB2DF9146AEE11CF8DAE006556EF32FB9B82AEFC72B9D3EBA189429452918A12F994FD6FFC8E26C4C9C40BB39E0\\\"}\"\n" +
//                                "}";
                        JSONObject objTs = new JSONObject(reponseStr);
                        Boolean successData = objTs.getBoolean("success");
                        String messageData = jsonobjectNullChangeStr(objTs.opt("message"));
                        String status = "";
                        if (successData) {
                            status = "success";
                        } else {
                            status = "fail";
                        }

                        WriteLog(uuid, pushApiConfigs.get(i).getServiceId(), "", "",
                                "", "", format.format(new Date()), reponseStr, status, messageData,
                                "1", metaConn);
                        if (success) {
                            ArrayList<String> sqls = new ArrayList<>();
                            sql = "select table_name from pz_del_table where type='all' ";
                            rs = MetaMysql.querySql(metaConn, sql);
                            while (rs.next()) {
                                sql = "truncate table " + rs.getString("table_name");
                                sqls.add(sql);
                            }
                            sql = "insert into czsy_zy.ztsj_hb_sjts_bf(tag_name,tag_time,tag_value)" +
                                    " select tag_name,tag_time,tag_value from " + pushApiConfigs.get(i).getFullTableName();
                            sqls.add(sql);
                            sql = "truncate table " + pushApiConfigs.get(i).getFullTableName();
                            sqls.add(sql);
                            DBSql.batchExecSql(dbConn, sqls);
                        }

                    }
                }
            }
            Thread.sleep(3000);
            System.out.println("----------------------此刻可以杀进程--------------------");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeDb(dbConn);
            closeDb(metaConn);
        }
    }

    //测试，没有实际意义
    public void httpPush2(ArrayList<PushApiConfig> pushApiConfigs) {
        String targetUrl = "http://localhost:8080/api/push";
        String jsonPayload = "{\"event\":\"message\",\"data\":{\"content\":\"Hello from JDK8\"}}";
        try {
            // 1. 创建连接
            URL url = new URL(targetUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 2. 设置请求参数
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Authorization", "Bearer test123");
            connection.setDoOutput(true);

            // 3. 写入请求体
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonPayload.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 4. 处理响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader br = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String responseLine;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }
                    System.out.println("响应结果: " + response.toString());
                }
            } else {
                System.err.println("请求失败，状态码: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static HashMap<String, String> getKeyValues(String str) {
        HashMap<String, String> map = new HashMap<String, String>();
        String[] strs = str.split(";");
        for (String s : strs) {
            String[] kv = s.split(":");
            map.put(kv[0], kv[1]);
        }
        return map;
    }

    public static void WriteLog(String batchId, String id, String userName, String reqTimeString,
                                String serviceCode, String reqBody, String resTime, String resBody, String resStatus,
                                String errDetail, String bz, Connection metaConn) throws Exception {
        String sql = "";
        if (bz.equals("0")) {
            sql = "insert into service_log(id,user_name,req_time,service_code,req_body) values(" +
                    "'" + batchId + "','" + userName + "','" + reqTimeString + "','" + serviceCode + "','" + reqBody +
                    "')";

        } else {
            sql = "update service_log set res_time='" + resTime + "',res_body='" + resBody + "',res_status='" + resStatus + "'," +
                    "err_detail='" + errDetail + "' where id='" + batchId + "'";
        }
        MetaMysql.execSql(metaConn, sql);
    }

    public static String jsonobjectNullChangeStr(Object object) throws Exception {
        String message = "";
        if (object == JSONObject.NULL) {
            message = "";
        }
        return message;
    }
}

